<?php
class GMAR
{
	static public function AccessCheck(){
		$role = (self::isGroupMode() ? GROUP_NAME . '@' : '') . MODULE_NAME . '/' . ACTION_NAME . ':' . $_SERVER['REQUEST_METHOD'];
		//dump($role);

		$roles = self::parseRole($_SESSION[C('USER_AUTH_KEY')]);
		//dump($roles);

		return in_array($role, $roles);
	}

	static private function isGroupMode(){
		return defined('GROUP_NAME');
	}

	static private function parseRole($role){
		if(is_string($role)) return array(self::_parseRole($role));
		if(is_array($role) && !empty($role)){
			foreach($role as $r){
				$_role[] = self::_parseRole($r);
			}
			return $_role;
		}
	}

	static private function _parseRole($r){
		if(!$r) return;

		//分离GROUP_NAME
		if(stripos($r, '@')){
			$arr = explode('@', $r);
			$group = empty($arr[0]) ? '*' : $arr[0];
			$r = $arr[1];
		}else{
			$group = "*";
		}

		//解析ROLE
		if($r=='*'){
			$r = "*/*:*";
		}else{
			//以(/)开始
			if(false === stripos($r, '/')) $r = '/' . $r;

			//以(:)结束
			if(false === stripos($r, ':')) $r .= ':';

			//替换(/)为*/
			if(0 == stripos($r, '/')) $r = str_replace('/', '*/', $r);

			//替换(:/)
			if(0 < stripos($r, '/:')) $r = str_replace('/:', '/*:', $r);

			//替换(:)
			if(preg_match('/\:$/', $r)) $r .= '*';
		}

		//支持分组
		if(self::isGroupMode()) $r = $group . '@' . $r;

		//替换(*)
		$find = array('*@', '*/', '/*', ':*');
		$replace = array(GROUP_NAME.'@', MODULE_NAME.'/', '/'.ACTION_NAME, ':'.$_SERVER['REQUEST_METHOD']);
		$r = str_replace($find, $replace, $r);

		//返回
		return $r;
	}
}
?>